package com.ita.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ita.dao.UserDao;
import com.ita.dao.impl.UserDaoImpl;
import com.ita.pojo.User;
import com.ita.util.FileUtil;
import com.ita.util.NumberUtil;

public class UserService {

	private ServletFileUpload upload;
	private UserDao userDao;

	public UserService() {
		userDao = new UserDaoImpl();
		DiskFileItemFactory factory = new DiskFileItemFactory(5 * 1024,
				new File("/temp"));
		upload = new ServletFileUpload(factory);
	}

	public String judge(HttpServletRequest request) throws IOException {

		User user = new User();
		try {
			List<FileItem> items = upload.parseRequest(request);
			if (userDao.checkUser(items.get(0).getString()) != 0) {
				return "username exist";
			}
			for (FileItem item : items) {
				if (item.isFormField()) {
					String field = item.getFieldName();
					String value = item.getString("utf-8");
					switch (field) {
					case "username":
						if (value.length() >= 8) {
							return "Length of username is not allowd to great than 8";
						}
						System.out.println(value);
						user.setUsername(value);
						break;
					case "salary":
						if (!NumberUtil.isDouble(value)) {
							return "Salary is not double";
						}
						user.setSalary(Double.parseDouble(value));
						break;
					case "birth":
						try {
							if (!NumberUtil.isBirth(value)) {
								return "BirthDay is illegal";
							}
						} catch (Exception e) {
							return "BirthDay is illegal";
						}
						user.setBirth(NumberUtil.parse2Date(value));
						break;
					case "sex":
						if (!("男".equals(value) || "女".equals(value))) {
							return "sex is illegal, only 1 or 0";
						}
						user.setSex(value);
						break;
					}
				} else {
					InputStream in=null;
					try {
						in = item.getInputStream();
					} catch (Exception e) {
						return "Not choose your image";
					}
					if (in.available() > (1024 * 50)) {
						return "img size out of 50KB";
					}
					user.setAvatar(FileUtil.readInputStream(in));
				}

			}
			userDao.addUser(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "legal";
	}
}
